package cn.imjzm.runcarserve.service.impl;
import cn.imjzm.runcarserve.mapper.LoginMapper;
import cn.imjzm.runcarserve.pojo.User;
import cn.imjzm.runcarserve.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginMapper loginMapper;  // 统一使用一个 Mapper 实例

    @Override
    public User userLogin(User user) {
        // 根据手机号查找用户
        User userFromDb = loginMapper.selectByEmail(user.getEmail());
        if (userFromDb == null) {
            return null;  // 用户不存在
        }

        // 验证密码
        if (!BCrypt.checkpw(user.getPassword(), userFromDb.getPassword())) {
            return null;  // 密码错误
        }

        // 清除敏感信息后返回
        userFromDb.setPassword(null);
        return userFromDb;
    }

    @Override
    public Boolean pwdEmailCheck(String email, String oldpwd) {
        User userFromDb = loginMapper.selectByEmail(email);
        if (userFromDb == null) {
            return false;  // 用户不存在
        }
        if (!BCrypt.checkpw(oldpwd, userFromDb.getPassword())) {
            return false;  // 密码错误
        }
        return true;
    }

    @Override
    public void changePwd(String newpwd, String email) {
        loginMapper.changePwd(newpwd , email);
    }

}
